#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import pandas as pd
from sicost.service.AbsRequestCallCppAPI import AbsRequestCallCppAPI
from sicost.BizConstants import BizConstants


class RequestMatWTAPI(AbsRequestCallCppAPI):
    """
        # NOTE 调用接口 将df1补全实际的出口重量，而不是理论出口重量
        # NOTE URL：http://190.2.245.29/BGM2M1/api/CallCpp

        NOTE 道理上不应该提供一个这么大而全的接口，应该case by case的提供小接口让开发者去调用
        NOTE 提供这样大而全的接口 属于偷懒过头了
    """

    __MAX_TIMES = 2

    __curr_times = 0

    table_source = None

    def __init__(self, p_mat_no=None, p_json_template_object=BizConstants.create_playload_sicost(), p_table_source='1'):
        """

        :param p_mat_no:
        :param p_json_template_object:
        :param p_table_source: 两个来源表， 1就是历史表，0就是当前表；0的都要最后写到1里面；所以保险一点就是1没查到  就去0里查一下 还没查到就诊查不到
        """
        super(RequestMatWTAPI, self).__init__(p_mat_no=p_mat_no, p_json_template_object=p_json_template_object)

        self.table_source = p_table_source
        # 现在我们这个接口传进去是这4个参数,第二个参数是1
        # 如果当1的时候没查到时，把1改成0再查一次
        self.payload['Tables'][0]['Rows'][0][1] = p_table_source

    def _on_before_request(self, p_payload=None, p_headers=None):
        """

        :return:
        """
        RequestMatWTAPI.__curr_times += 1

    def _on_request_fail(self, p_exception=None):
        """

        :param p_exception:
        :return:
        """
        self.logger.error('RequestMatWTAPI._on_request_fail---->>\n%s' % (str(p_exception)))
        return RequestMatWTAPI.__fail_results()

    def _on_parsing(self, p_payload=None, p_response_dict=None):
        """

        :param p_payload:
        :param p_response_dict:
        :return:
        """
        self.logger.info('RequestMatWTAPI._on_parsing')

        try:
            columns = p_response_dict['Tables'][0]['Columns']
            index = columns.index(next(x for x in columns if x['Name'] == 'MAT_WT'))
            v = p_response_dict['Tables'][0]['Rows'][0][index]
            success = True
        except Exception as e:
            v = -1
            success = False
            self.logger.error('\n')
            self.logger.error(
                f"mat_no={self.mat_no}, table_source={self.table_source}, curr_times={RequestMatWTAPI.__curr_times}, MAX_TIMES={RequestMatWTAPI.__MAX_TIMES}")
            self.logger.error(str(p_payload))
            self.logger.error(str(p_response_dict))
            self.logger.error(str(e))
            self.logger.error('\n')

        if success:
            RequestMatWTAPI.__curr_times = 0
        else:
            if RequestMatWTAPI.__curr_times < RequestMatWTAPI.__MAX_TIMES:
                self.logger.info(
                    f'mat_no={self.mat_no}, table_source={self.table_source}, RequestMatWTAPI-try-again-request_times={RequestMatWTAPI.__curr_times}')
                success, v = RequestMatWTAPI(p_mat_no=self.mat_no,
                                             p_json_template_object=self.json_template_object,
                                             p_table_source='0').request()
                self.logger.info(
                    f'mat_no={self.mat_no}, table_source={self.table_source}, RequestMatWTAPI-try-again-request_times={RequestMatWTAPI.__curr_times}, success={success}, v={v}')
            else:
                RequestMatWTAPI.__curr_times = 0

        return success, v

    def _on_parse_fail(self, p_response=None, p_exception=None):
        """

        :param p_response:
        :param p_exception:
        :return:
        """
        self.logger.error('RequestMatWTAPI._on_parse_fail---->>\n%s\n%s' % (str(p_response), str(p_exception)))
        return RequestMatWTAPI.__fail_results()

    @staticmethod
    def __fail_results():
        """
        :return:
        """
        return False, -1
